<!-- 用户管理 -->
<template>
  <PageContainer title="用户管理">
    <!-- 搜索和操作区 -->
    <div class="search-operate">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input v-model="searchForm.keyword" placeholder="请输入用户名/手机号搜索" prefix-icon="el-icon-search"
            class="search-input"></el-input>
        </el-col>
        <el-col :span="12" class="operate-buttons">
          <el-select v-model="searchForm.role" placeholder="请选择角色" class="role-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="普通用户" value="user"></el-option>
            <el-option label="商家" value="merchant"></el-option>
            <el-option label="医生" value="doctor"></el-option>
          </el-select>
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加用户
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 用户表格 -->
    <el-table :data="userList" border stripe :loading="loading" style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="用户ID" prop="id" width="80" align="center"></el-table-column>
      <el-table-column label="用户名" prop="username" width="120"></el-table-column>
      <el-table-column label="手机号" prop="phone" width="130" align="center"></el-table-column>
      <el-table-column label="邮箱" prop="email" width="200"></el-table-column>
      <el-table-column label="角色" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getRoleTagType(scope.row.role)">
            {{ getRoleLabel(scope.row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" align="center"></el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" style="color: red;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <TablePagination :total="total" :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" style="margin-top: 20px; text-align: right;"></TablePagination>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog :title="isEdit ? '编辑用户' : '添加用户'" :visible.sync="dialogVisible" width="500px"
      :before-close="handleDialogClose">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" type="email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role" v-if="!isEdit">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="普通用户" value="user"></el-option>
            <el-option label="商家" value="merchant"></el-option>
            <el-option label="医生" value="doctor"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-value="1" inactive-value="0" active-text="启用"
            inactive-text="禁用"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '../../components/common/PageContainer.vue'
import TablePagination from '../../components/common/TablePagination.vue'
import { getUserList, addUser, editUser, deleteUser, batchDeleteUser, updateUserStatus } from '../../api/user'

// 搜索表单
const searchForm = reactive({
  keyword: '',
  role: ''
})

// 表格数据
const userList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)
const selectedIds = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  username: '',
  phone: '',
  email: '',
  role: 'user',
  password: '',
  status: 1
})

// 表单校验规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度在4-20位之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20位之间', trigger: 'blur' }
  ]
})

// 角色标签类型
const getRoleTagType = (role) => {
  const roleTypeMap = {
    user: 'info',
    merchant: 'success',
    doctor: 'primary'
  }
  return roleTypeMap[role] || 'default'
}

// 角色标签文本
const getRoleLabel = (role) => {
  const roleLabelMap = {
    user: '普通用户',
    merchant: '商家',
    doctor: '医生',
    super_admin: '超级管理员'
  }
  return roleLabelMap[role] || '未知角色'
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const res = await getUserList({
      keyword: searchForm.keyword,
      role: searchForm.role,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    userList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchUserList()
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchUserList()
}

// 选择改变（批量操作）
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
}

// 添加用户
const handleAdd = () => {
  isEdit.value = false
  // 重置表单
  form.id = ''
  form.username = ''
  form.phone = ''
  form.email = ''
  form.role = 'user'
  form.password = ''
  form.status = 1
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  isEdit.value = true
  // 填充表单
  form.id = row.id
  form.username = row.username
  form.phone = row.phone
  form.email = row.email
  form.role = row.role
  form.status = row.status
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该用户吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteUser(row.id)
    ElMessage.success('删除成功')
    fetchUserList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedIds.value.length}个用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await batchDeleteUser(selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    fetchUserList()
  } catch (error) {
    ElMessage.error('批量删除失败')
  }
}

// 改变用户状态
const handleStatusChange = async (row) => {
  try {
    await updateUserStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success(`用户已${row.status === 1 ? '启用' : '禁用'}`)
  } catch (error) {
    // 失败时回滚状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 表单提交
const handleFormSubmit = async () => {
  try {
    await formRef.value.validate()
    if (isEdit) {
      // 编辑用户
      await editUser(form)
      ElMessage.success('编辑用户成功')
    } else {
      // 添加用户
      await addUser(form)
      ElMessage.success('添加用户成功')
    }
    dialogVisible.value = false
    fetchUserList()
  } catch (error) {
    ElMessage.error(isEdit ? '编辑用户失败' : '添加用户失败')
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}

// 页面挂载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped lang="scss">
.search-operate {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;

  .search-input {
    width: 100%;
  }

  .operate-buttons {
    display: flex;
    gap: 10px;
    align-items: center;

    .role-select {
      width: 160px;
    }
  }
}
</style>